var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');


var index = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//app.use(logger('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('请求URL非法');
  err.status = 200;
  res.end();
  //next(err);
});

function  Hexstring2btye(str){
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
        return null;
    }
    len /= 2;
    var hexA = "";
    for (var i = 0; i < len; i++) {
        var s = str.substr(pos, 2);
        var v = parseInt(s, 16);
        hexA=hexA+v;
        pos += 2;
    }
    return hexA;
}

var npm = require('getmac');//获取mac地址
var deviceprocess=require('./routes/deviceprc');

var schedule = require("node-schedule");
var rule     = new schedule.RecurrenceRule();
var times = [];
for(var i=0; i<60; i+=5){
    times.push(i);
}
rule.second  = times;

function generateFile() {

    //获取机器mac地址
    npm.getMac(function(err,macAddress){
        if (err)  throw err;
        var mac = macAddress; //获取mac地址
        mac=mac.replace(/-/g,'');
        mac=mac.replace(/:/g,'');
        var deviceid=Hexstring2btye(mac);
        deviceid=deviceid.substr(deviceid.length-8, 8);

        schedule.scheduleJob(rule, function(){
            deviceprocess.process(deviceid, mac);
        });

        deviceprocess.processHeartbeat(deviceid, macAddress);
    });
}
generateFile();




